package org.homonoia.model.query;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;

public class Query implements Serializable {

    /**
	 * 
	 */
    private static final long serialVersionUID = -1427371657247391798L;

    private String table;
    private String column;
    private ArrayList<String> searchTerms;

    public Query(final String table, final String column, final ArrayList<String> searchTerms) {
	super();

	setTable(table);
	setColumn(column);
	setSearchTerms(searchTerms);
    }

    public final String getTable() {
	return table;
    }

    public final String getColumn() {
	return column;
    }

    public final ArrayList<String> getSearchTerms() {
	return searchTerms;
    }

    public void setTable(final String table) {
	validateSQL(table);
	this.table = table;
    }

    public void setColumn(final String column) {
	validateSQL(column);
	this.column = column;
    }

    public void setSearchTerms(final ArrayList<String> searchTerms) {
	validateSearchTerms(searchTerms);
	this.searchTerms = searchTerms;
    }

    private void validateState() {
	validateSQL(this.table);
	validateSQL(this.column);
	validateSearchTerms(this.searchTerms);
    }

    private void validateSQL(String sql) {
	if (sql.contains(".") || sql.contains("\\") || sql.contains("/")) {
	    throw new IllegalArgumentException("SQL fields cannot contain '.', '/' or '\'");
	}
    }

    private void validateSearchTerms(ArrayList<String> searchTerms) {
	for (String s : searchTerms) {
	    if (s.contains("*")) {
		throw new IllegalArgumentException("Search Terms cannot be wildcards");
	    }
	}
    }

    private void readObject(ObjectInputStream is) throws ClassNotFoundException, IOException {
	is.defaultReadObject();

	validateState();
    }

    private void writeObject(ObjectOutputStream os) throws IOException {
	os.defaultWriteObject();
    }
}
